package com.novel.disk.framework.filter;

import com.alibaba.fastjson.JSONObject;
import com.novel.disk.common.Result;
import com.novel.disk.common.ServletUtils;
import com.novel.disk.entity.SysUser;
import com.novel.disk.framework.config.LoginProperties;
import com.novel.disk.framework.exception.LoginTimeoutException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 登录过滤器
 *
 * @author novel
 * @date 2020/7/24
 */
public class LoginFilter extends HandlerInterceptorAdapter {

    private final RestTemplate restTemplate;
    private final LoginProperties loginProperties;

    public LoginFilter(RestTemplate restTemplate, LoginProperties loginProperties) {
        this.restTemplate = restTemplate;
        this.loginProperties = loginProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = loginProperties.getUrl() + "/system/user/getUserInfo";
        String token = request.getHeader("Authorization");

        HttpHeaders header = new HttpHeaders();
        header.set("Authorization", token);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(header);

        ResponseEntity<Result> entity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Result.class);
        HttpHeaders headers = entity.getHeaders();
        List<String> authorization = headers.get("Authorization");
        if (authorization != null && authorization.size() > 0) {
            String newToken = authorization.get(0);
            response.addHeader("Authorization", newToken);
        }
        Result result = entity.getBody();
        if (result != null && result.isResult()) {
            String json = JSONObject.toJSONString(result.getData());
            SysUser sysUser = JSONObject.parseObject(json, SysUser.class);
            request.setAttribute("user", sysUser);
            return true;
        }
        if (ServletUtils.isAjaxRequest(request)) {
            throw new LoginTimeoutException("用户未登录", 401);
        }
        return false;
    }
}
